<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Backend\LoginController;
use App\Models\Admin;
use Closure;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Redis;

class UserValidate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $routeName = $request->route()->getName();
        $userId = Cookie::get(LoginController::COOKIE_LOGIN_KEY);
        if ($userId) {
            $info = Admin::find($userId);
        }
        if ($routeName == 'backendLogin') {
            if($userId && $info) {
                return redirect()->route('backendIndex');
            }
        } else {
            if (!$userId) {
                return redirect()->route('backendLogin');
            } else {
                if (!$info)
                    return redirect()->route('backendLogin');
            }
        }

        return $next($request);
    }
}
